<template>
  <el-container style="height: 90vh">
    <!-- 左侧树形文件系统 -->
    <div
      ref="leftPanel"
      :style="{ width: leftWidth + 'px' }"
      style="
        background-color: #ffffff;
        padding: 20px;
        position: relative;
        border-right: 1px solid #e4e7ed;
      "
    >
      <!-- 树形列表 -->
      <el-input
        v-model="treeFilterText"
        placeholder="输入关键字过滤"
        style="margin-bottom: 10px"
      ></el-input>
      <el-tree
        ref="fileTree"
        show-checkbox
        @check="handleFileCheck"
        node-key="id"
        :check-strictly="true"
        :default-expand-all="true"
        :expand-on-click-node="false"
        highlight-current
        :data="folderTree"
        :props="{
          label: 'name',
          children: 'children',
          isLeaf: (data) => data.type === 'file',
        }"
        :default-expanded-keys="defaultExpandedKeys"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <!-- 动态图标 -->
            <i
              :class="
                data.type === 'folder' ? 'el-icon-folder' : 'el-icon-document'
              "
            />&nbsp;&nbsp;
            <span>{{ node.label }}</span>
          </span>
        </template>
      </el-tree>
      <!-- 拖动分隔条 -->
      <div class="resize-handle" @mousedown="startResize"></div>
    </div>

    <!-- 中间用户/角色列表 -->
    <div class="center-panel">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="用户" name="user">
          <!-- <el-input v-model="userFilter" placeholder="搜索用户" /> -->
          <el-table
            ref="userTable"
            :data="filteredUsers"
            @current-change="handleUserSelect"
            highlight-current-row
            row-key="userId"
            :current-row-key="selectedUser ? selectedUser.userId : null"
            @selection-change="handleUserSelection"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column width="205" prop="userName" label="用户名" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="角色" name="role">
          <!-- <el-input v-model="roleFilter" placeholder="搜索角色" /> -->
          <el-table
            :data="filteredRoles"
            @current-change="handleRoleSelect"
            highlight-current-row
            :current-row-key="selectedRole ? selectedRole.roleId : null"
            @selection-change="handleRoleSelection"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column width="205" prop="roleName" label="角色名" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 右侧权限设置 -->
    <div class="right-panel">
      <el-card shadow="never">
        <!-- 权限表格 -->
        <el-table
          ref="permissionTable"
          :data="permissionList"
          highlight-current-row
        >
          <el-table-column prop="name" label="权限名称" width="140" />
          <el-table-column label="状态" width="130" align="center">
            <template #default="{ row }">
              <el-switch
                v-model="row.enabled"
                active-color="#409eff"
                @change="handleSwitchChange(row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-button :loading="saving" type="primary" @click="savePermissions">
        <i class="el-icon-check"></i>
        {{ saving ? "保存中..." : "保存权限" }}
      </el-button>
    </div>
  </el-container>
</template>

<script>
import { batchSave, getPermission } from "@/api/zhishiku/permission";
import { getFolderTree } from "@/api/zhishiku/folder";
import { listUser } from "@/api/system/user";
import { listRole } from "@/api/system/role";

export default {
  data() {
    return {
      // 防抖相关属性
      debounceTimer: null,
      isPermissionRequesting: false, // 请求锁

      saving: false,

      currentUserId: this.$store.state.user.id, // 当前用户ID

      permissionList: [
        { name: "删除", code: "canDelete", enabled: false },
        { name: "查看", code: "canView", enabled: true },
        { name: "编辑", code: "canEdit", enabled: false },
        { name: "添加", code: "canAdd", enabled: false },
      ],

      selectedFiles: [], // 选中的文件ID
      selectedFolders: [], // 选中的文件夹ID
      selectedUsers: [], // 选中的用户ID
      selectedRoles: [], // 选中的角色ID
      currentPermissions: {
        canDelete: false,
        canView: true,
        canEdit: false,
        canAdd: false,
      },

      folderTree: [],

      selectedUser: null,

      // 用户角色相关数据
      activeTab: "user",
      userFilter: "",
      roleFilter: "",
      users: [],
      roles: [],
      selectedTarget: null, // { type: 'user'|'role', id: number }
      selectedNode: null, // 当前选中的文件/文件夹节点
      checkedNodes: [], // 多选节点
      checkedKeys: [], // 多选ID

      // 树形文件系统数据
      fileTreeData: [], // 从后端获取
      currentNodeId: 0, //当前被选中节点的id
      treeProps: {
        label: "label",
        children: "children",
      },
      treeFilterText: "", // 树形列表过滤关键字

      // 角色数据
      roles: [], // 从后端获取
      selectedRole: null, // 选中的人员角色id
      selectedRoleBody: null, //选中当前人员角色对象
      roleFilterText: "", // 人员角色过滤关键字

      // 权限数据
      selectedPermissions: [], // 选中的权限
      permissionFilterText: "", // 权限过滤关键字

      // // 左侧面板宽度
      leftWidth: 320, // 默认宽度
      isResizing: false, // 是否正在调整宽度
    };
  },
  computed: {
    // 默认展开树形节点
    defaultExpandedKeys() {
      const keys = [];
      // 第一层节点
      this.folderTree.forEach((node) => {
        keys.push(node.id);
        // 第二层节点
        if (node.children?.length) {
          node.children.forEach((child) => keys.push(child.id));
        }
      });
      return keys;
    },

    // 过滤后的用户列表
    filteredUsers() {
      return this.users.filter(
        (u) =>
          u.nickName.toLowerCase().includes(this.userFilter.toLowerCase()) ||
          u.userName.toLowerCase().includes(this.userFilter.toLowerCase())
      );
    },
    // 过滤后的角色列表
    filteredRoles() {
      return this.roles.filter(
        (r) =>
          r.roleName.toLowerCase().includes(this.roleFilter.toLowerCase()) ||
          r.roleKey.toLowerCase().includes(this.roleFilter.toLowerCase())
      );
    },
  },

  watch: {
    // 监听用户和角色选择变化
    selectedUsers: {
      handler(newVal) {
        if (newVal.length === 0 && this.selectedRoles.length === 0) {
          this.clearSelections();
        }
      },
      deep: true,
    },
    selectedRoles: {
      handler(newVal) {
        if (newVal.length === 0 && this.selectedUsers.length === 0) {
          this.clearSelections();
        }
      },
      deep: true,
    },

    // 树形列表过滤
    treeFilterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  async created() {
    // 加载树数据
    await this.loadFolderTree();

    await this.loadUsers(); // 加载用户数据
    await this.loadRoles(); // 加载角色数据

    // 确保用户数据存在后再执行自动选择
    await this.autoSelectCurrentUser();
  },
  methods: {
    // 自动选择当前用户
    async autoSelectCurrentUser() {
      if (!this.users || this.users.length === 0) return;

      const currentUser = this.users.find(
        (u) =>
          u.userId === this.currentUserId ||
          u.userName === this.$store.state.user.name
      );

      if (currentUser) {
        this.$nextTick(() => {
          try {
            if (this.$refs.userTable) {
              // 清除之前的选择
              this.$refs.userTable.clearSelection();

              // 设置勾选状态
              this.$refs.userTable.toggleRowSelection(currentUser, true);

              // 触发选择事件
              this.handleUserSelection([currentUser]);
            }
          } catch (error) {
            console.error("自动选择错误:", error);
            this.$message.error("自动选择失败");
          }
        });
      }
    },

    // 处理文件树多选
    handleFileCheck() {
      // 获取所有已选中的节点
      const checkedNodes = this.$refs.fileTree.getCheckedNodes(false);

      // 增强调试输出（格式化+类型分类）
      // console.groupCollapsed("[Tree] 选中节点详情");
      // console.log("完整节点对象：", JSON.parse(JSON.stringify(checkedNodes)));
      // console.log("文件ID：", this.selectedFiles);
      // console.log("文件夹ID：", this.selectedFolders);
      // console.groupEnd();

      // 获取半选中父节点
      const halfCheckedKeys = this.$refs.fileTree.getHalfCheckedKeys();
      console.debug("半选中父节点ID：", halfCheckedKeys);

      this.selectedFiles = checkedNodes
        .filter((n) => n.type === "file")
        .map((n) => n.id);
      this.selectedFolders = checkedNodes
        .filter((n) => n.type === "folder")
        .map((n) => n.id);
    },

    // 处理用户多选
    async handleUserSelection(selection) {
      this.$refs.fileTree.setCheckedKeys([]);
      this.selectedFiles = [];
      this.selectedFolders = [];

      // 清除之前的防抖计时器
      clearTimeout(this.debounceTimer);

      // 设置防抖延迟（300毫秒）
      this.debounceTimer = setTimeout(async () => {
        try {
          // 请求锁检查
          if (this.isPermissionRequesting) {
            console.warn("已有权限请求在处理中");
            return;
          }

          this.$refs.fileTree.setCheckedKeys([]);
          this.selectedFiles = [];
          this.selectedFolders = [];

          this.selectedUsers = selection.map((u) => u.userId);

          // 空选择处理
          if (this.selectedUsers.length === 0) {
            this.clearSelections();
            return;
          }

          // 设置请求锁
          this.isPermissionRequesting = true;

          const { data } = await getPermission({
            userIds: this.selectedUsers,
            refType: 0,
          });

          // 获取完整的树节点信息
          const allNodes = this.$refs.fileTree.store.nodesMap;

          // 分离文件和文件夹ID
          const processedData = {
            fileIds: data.refIds
              .filter((id) => allNodes[id]?.data?.type === "file")
              .map(Number),
            folderIds: data.refIds
              .filter((id) => allNodes[id]?.data?.type === "folder")
              .map(Number),
            ...data,
          };

          this.updatePermissions(processedData);
        } catch (error) {
          console.error("权限加载失败:", error);
          this.clearSelections(); // 清空状态
        } finally {
          // 释放请求锁
          this.isPermissionRequesting = false;
        }
      }, 300); // 防抖延迟时间
    },

    // 处理角色多选
    async handleRoleSelection(selection) {
      try {
        this.selectedRoles = selection.map((r) => r.roleId);
        // 当没有选中角色时清空状态
        if (this.selectedRoles.length === 0) {
          this.clearSelections();
          return;
        }

        if (this.selectedRoles.length === 0) return;

        const { data } = await getPermission({
          roleIds: this.selectedRoles,
          refType: 0,
        });

        // 统一数据验证
        if (!data || !Array.isArray(data.refIds)) {
          console.error("无效的角色权限数据:", data);
          throw new Error("角色权限接口返回数据格式异常");
        }

        // 获取树节点映射
        const allNodes = this.$refs.fileTree.store.nodesMap;

        // 处理数据格式（与用户处理逻辑保持一致）
        const processedData = {
          fileIds: data.refIds
            .filter((id) => allNodes[id]?.data?.type === "file")
            .map(Number),
          folderIds: data.refIds
            .filter((id) => allNodes[id]?.data?.type === "folder")
            .map(Number),
          ...data,
        };

        this.updatePermissions(processedData);
      } catch (error) {
        console.error("角色权限加载失败:", error);
        this.clearSelections(); // 出错时也清空状态
      }
    },

    // 新增清空状态方法
    clearSelections() {
      // 清空树选中
      this.$refs.fileTree.setCheckedKeys([]);
      // 清空文件选择记录
      this.selectedFiles = [];
      this.selectedFolders = [];
      // 重置权限开关
      this.permissionList.forEach((p) => (p.enabled = false));
      // 清空当前权限
      this.currentPermissions = {
        canDelete: false,
        canView: false, // 默认关闭查看权限
        canEdit: false,
        canAdd: false,
      };
    },

    updatePermissions(data) {
      // 获取完整的树结构数据
      const allNodes = this.$refs.fileTree.store.nodesMap;

      // 收集需要勾选的所有节点ID（包括父级文件夹）
      const allCheckedIds = new Set();

      // 处理原始权限ID
      const processIds = (ids) => {
        ids.forEach((id) => {
          // 添加当前节点
          allCheckedIds.add(id);
        });
      };

      // 处理文件ID
      processIds(data.fileIds.map(Number));
      // 处理文件夹ID
      processIds(data.folderIds.map(Number));
      // 处理普通refIds
      processIds((data.refIds || []).map(Number));

      console.log("最终需要勾选的ID（包含父级）:", [...allCheckedIds]);

      this.$nextTick(() => {
        if (this.$refs.fileTree) {
          this.$refs.fileTree.setCheckedKeys([...allCheckedIds], {
            emitEvent: false, // 保留不触发事件
          });

          // 手动同步选中状态
          const checkedNodes = this.$refs.fileTree.getCheckedNodes(false);
          this.selectedFiles = checkedNodes
            .filter((n) => n.type === "file")
            .map((n) => n.id);
          this.selectedFolders = checkedNodes
            .filter((n) => n.type === "folder")
            .map((n) => n.id);
        }
      });

      // this.$nextTick(() => {
      //   if (this.$refs.fileTree) {
      //     // 设置勾选时应包含所有父级节点
      //     this.$refs.fileTree.setCheckedKeys([...allCheckedIds], {
      //       emitEvent: false,
      //     });

      //     // 展开所有相关父节点
      //     [...allCheckedIds].forEach((id) => {
      //       const node = this.$refs.fileTree.getNode(id);

      //     });
      //   }
      // });

      // 更新权限开关
      this.permissionList.forEach((p) => {
        p.enabled = data[p.code] ?? false;
      });

      // 更新当前权限
      console.log("更新权限: 当前权限", this.permissionList);
    },

    // 权限开关处理
    handleSwitchChange(row) {
      this.currentPermissions = {
        ...this.currentPermissions,
        [row.code]: row.enabled,
      };
      console.log("当前权限状态更新:", this.currentPermissions);
    },

    // 保存权限
    async savePermissions() {
      console.log("开始保存权限...");
      if (this.isPermissionRequesting) {
        this.$message.warning("权限数据加载中，请稍后重试");
        return;
      }
      // 新增验证逻辑
      if (this.selectedUsers.length + this.selectedRoles.length === 0) {
        this.$message.error("请至少选择一个用户或角色");
        return;
      }
      if (this.selectedFiles.length + this.selectedFolders.length === 0) {
        this.$message.error("请至少选择一个文件或文件夹");
        return;
      }

      // 核心修改：分类型提交资源
      const requests = [];

      // 处理文件类型（refType=0）
      if (this.selectedFiles.length > 0) {
        const dto = {
          refType: 0, // 文件类型
          refIds: this.selectedFiles, // 文件ID列表
          userIds: this.selectedUsers,
          roleIds: this.selectedRoles,
          ...this.currentPermissions,
        };
        requests.push(batchSave(dto));
      }

      // 处理文件夹类型（refType=1）
      if (this.selectedFolders.length > 0) {
        const dto = {
          refType: 1, // 文件夹类型
          refIds: this.selectedFolders, // 文件夹ID列表
          userIds: this.selectedUsers,
          roleIds: this.selectedRoles,
          ...this.currentPermissions,
        };
        requests.push(batchSave(dto));
      }

      try {
        await Promise.all(requests);
        this.$message.success("权限保存成功");
      } catch (error) {
        console.error("保存失败:", error);
        this.$message.error("保存失败: " + (error.message || "未知错误"));
      } finally {
        this.saving = false;
      }
    },

    // 处理权限选择
    handlePermissionToggle(row) {
      const index = this.permissionList.findIndex((p) => p.code === row.code);
      if (index > -1) {
        this.$set(this.permissionList, index, { ...row });
      }
    },

    // 处理权限开关切换
    handlePermissionToggle(row) {
      this.$nextTick(() => {
        this.currentPermissions = this.permissionList
          .filter((item) => item.enabled)
          .map((item) => item.code);
      });
    },

    // 加载用户列表
    async loadUsers() {
      try {
        const res = await listUser({ pageNum: 1, pageSize: 1000 });
        this.users = res.rows;
        console.log("加载的用户列表:", this.users); // 添加日志
        await this.$nextTick();
        return Promise.resolve(); // 返回Promise
      } catch (error) {
        console.error("用户加载失败:", error);
        return Promise.reject(error);
      }
    },

    // 加载角色列表
    async loadRoles() {
      try {
        const res = await listRole({
          pageNum: 1,
          pageSize: 1000, // 根据实际情况调整
        });
        this.roles = res.rows;
      } catch (error) {
        this.$message.error("角色加载失败");
      }
    },
    // 处理用户选择
    handleUserSelect(user) {
      this.selectedUser = user;
      this.selectedRole = null; // 清除角色选择
      this.selectedTarget = user
        ? {
            type: "user",
            id: user.userId,
          }
        : null;
      // this.loadPermissions();
    },

    // 角色选择处理
    handleRoleSelect(role) {
      this.selectedRole = role;
      this.selectedUser = null; // 清除用户选择
      this.selectedTarget = role
        ? {
            type: "role",
            id: role.roleId,
          }
        : null;
    },

    // 节点单击事件
    handleNodeClick(nodeData) {
      console.log("当前选中节点数据:", nodeData);
      this.selectedNode = nodeData;
    },

    loadFolderTree() {
      getFolderTree().then((res) => {
        // 过滤文件节点（处理嵌套结构）
       
        this.folderTree = res.data;
        resolve();
      });
    },

    // loadFolderTree() {
    //   return new Promise((resolve) => {
    //     getFolderTree().then((res) => {
    //       this.folderTree = res.data;
    //       resolve();
    //     });
    //   });
    // },

    //设置高亮属性
    addHighlightProperty(data) {
      return data.map((item) => {
        // 如果有子节点，递归处理
        if (item.children && item.children.length > 0) {
          item.children = this.addHighlightProperty(item.children);

          // 检查子节点是否有被选中的
          const hasHighlightedChild = item.children.some(
            (child) => child.isHighlighted
          );

          // 设置当前节点的 isHighlighted 状态
          item.isHighlighted = item.isSelected || hasHighlightedChild;
        } else {
          // 如果没有子节点，直接根据 isSelected 设置 isHighlighted
          item.isHighlighted = item.isSelected || false;
        }

        return item;
      });
    },

    // 树形列表过滤方法
    filterTreeNode(value, data) {
      if (!value) return true;
      return data.label.toLowerCase().includes(value.toLowerCase());
    },

    // 树节点点击事件
    handleTreeNodeClick(data) {
      this.currentNodeId = data.id;
      //data.isSelected = !data.isSelected; // 切换选中状态
      //this.updateHighlight(data, data.isSelected);
      //this.updateParentHighlight(data);
    },

    // 更新树节点高亮状态
    updateHighlight(data, isSelected) {
      data.isHighlighted = isSelected;
      if (data.children) {
        data.children.forEach((child) => {
          this.updateHighlight(child, isSelected);
        });
      }
    },

    // 更新父级高亮状态
    updateParentHighlight(data) {
      const parent = this.findParent(data);
      if (parent) {
        const hasHighlightedChild = parent.children.some(
          (child) => child.isHighlighted
        );
        parent.isHighlighted = hasHighlightedChild;
        this.updateParentHighlight(parent);
      }
    },

    // 查找父节点
    findParent(data, tree = this.fileTreeData) {
      for (let node of tree) {
        if (node.children && node.children.includes(data)) {
          return node;
        }
        if (node.children) {
          const found = this.findParent(data, node.children);
          if (found) return found;
        }
      }
      return null;
    },

    // 处理人员角色点击
    handleRoleClick(role) {
      this.roles.forEach((r) => {
        r.isHighlighted = r.id === role.id; // 单选高亮
      });
      this.selectedRole = role.id; // 更新选中角色
      this.selectedRoleBody = role; //更新选中角色对象
    },

    // 处理权限点击
    handlePermissionClick(permission) {
      // 使用 Vue.set 确保响应式更新
      if (permission.isHighlighted === 0) {
        permission.isHighlighted = 1;
      } else {
        permission.isHighlighted = 0;
      }

      //控制选中权限列表
      this.selectedPermissions = this.permissions
        .filter((item) => item.isHighlighted === 1) // 筛选出 isHighlighted === 1 的项
        .map((item) => item.id); // 提取 id 属性值
    },

    // 取消操作
    cancel() {
      console.log("取消成功");
    },

    // 开始调整宽度
    startResize(event) {
      this.isResizing = true;
      document.addEventListener("mousemove", this.resize);
      document.addEventListener("mouseup", this.stopResize);
    },

    // 调整宽度
    resize(event) {
      if (this.isResizing) {
        const newWidth = event.clientX;
        if (newWidth > 200 && newWidth < 600) {
          this.leftWidth = newWidth;
        }
      }
    },

    // 停止调整宽度
    stopResize() {
      this.isResizing = false;
      document.removeEventListener("mousemove", this.resize);
      document.removeEventListener("mouseup", this.stopResize);
    },
  },
};
</script>

<style scoped>
/* 整体容器调整 */
.el-container {
  background-color: #f5f7fa; /* 增加背景色 */
  padding: 20px;
  gap: 16px; /* 增加面板间距 */
}

/* 左侧面板美化 */
.left-panel {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 16px !important;
  transition: box-shadow 0.3s;
}

/* 树形结构优化 */
.custom-tree-node {
  font-size: 14px;
  color: #606266;
  transition: color 0.3s;
}
.custom-tree-node:hover {
  color: #409eff;
}
.folder-icon {
  filter: opacity(0.8); /* 图标颜色柔和化 */
}

/* 中间面板优化 */
.center-panel {
  width: 300px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 16px;
}
.el-tabs {
  --el-tabs-header-height: 40px;
}
.el-tabs__item {
  font-weight: 500;
}
.el-table {
  margin-top: 12px;
  border-radius: 6px;
  overflow: hidden;
}
.el-table::before {
  /* 移除默认边框 */
  height: 0;
}

/* 右侧面板优化 */
.right-panel {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.el-card {
  border: none !important;
  flex: 1;
}
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

/* 开关样式优化 */
.el-switch.is-checked :deep(.el-switch__core) {
  background-color: #409eff !important;
  border-color: #409eff !important;
}

/* 按钮样式统一 */
.el-button--primary {
  padding: 10px 24px;
  align-self: flex-end;
}

/* 分隔条美化 */
.resize-handle {
  width: 3px;
  background: #e4e7ed;
  transition: background 0.3s;
}
.resize-handle:hover {
  background: #409eff;
}

/* 表格行高优化 */
.el-table__row td {
  padding: 12px 0 !important;
}

/* 选中状态强化 */
.current-row td {
  background-color: rgba(64, 158, 255, 0.08) !important;
  font-weight: 500;
}

::v-deep
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  background-color: rgba(64, 158, 255, 0.2) !important;
  color: #409eff !important;
}

::v-deep .el-icon-folder {
  font-size: 18px; /* 默认大小14px */
  margin-right: 3px;
  vertical-align: middle;
  color: #f5a623 !important;
}

/* 文件特殊颜色 */
::v-deep .el-icon-document {
  font-size: 20px; /* 默认大小14px */
  margin-right: 8px;
  vertical-align: middle;
  color: #409eff !important;
}

/* 确保选中行高亮 */
::v-deep .el-table__row.current-row {
  background-color: #f0f7ff !important;
}

/* 选中复选框样式 */
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #409eff;
  border-color: #409eff;
}
</style>
